//
//  IGCommentVC.m
//  jingdongfang
//
//  Created by BOE on 2018/5/15.
//  Copyright © 2018年 BOE-SBG-CTO. All rights re served.
//

#import "IGCommentVC.h"
#import "IGCommentCell.h"
#import "IWTextView.h"
#import "IGArtWorkModel.h"
#import "IGCommentZuoPinCell.h"
#import "IGCommentBean.h"

@interface IGCommentVC ()<UITableViewDelegate, UITableViewDataSource, UITextViewDelegate> {
    BOOL isRecomment;
    BOOL isTop;
    CGRect selRect;
    CGFloat currtOff;
    BOOL moreSelected;
}

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *hotComments;
@property (nonatomic, strong) NSMutableArray *newsComments;
@property (nonatomic, assign) IGCommentPageType type;
@property (nonatomic, copy) NSString *lastQueryId;
@property (nonatomic, strong) IGCommentBean *replayTheSeletedCellModel;
@property (nonatomic, strong) UIView *imView;
@property (nonatomic, strong) IWTextView *imText;

@property (nonatomic, strong) IGBaseModel *baseModel;
@property (nonatomic, copy) NSString *productId;

@end

@implementation IGCommentVC

- (instancetype)initWithType:(IGCommentPageType)type baseModel:(IGBaseModel *)baseModel
{
    self = [super init];
    if (self) {
        self.type = type;
        self.baseModel = baseModel;
        if (self.type == IGCommentPageTypeZuopin) {
            IGArtWorkModel *model = (IGArtWorkModel *)baseModel;
            self.productId = model.aId;
        } else if (self.type == IGCommentPageTypeHuaDan) {
            IGDrawModel *model = (IGDrawModel *)baseModel;
            self.productId = model.drawId;
        }
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initData];
    [self addNotification];
    [self createUI];
    [self dataRequest];
}

- (void)initData {
    _page = 0;
    _lastQueryId = @"";
    self.hotComments = [NSMutableArray array];
    self.newsComments = [NSMutableArray array];
}

- (void)addNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)dataRequest {
    IGNCommentListApi *listApi = [IGNCommentListApi new];
    listApi.type = self.type;
    listApi.productId = self.productId;
    listApi.lastQueryId = self.lastQueryId;
    listApi.pageNum = self.page;
    __weak typeof(self) weakSelf = self;
    [listApi startWithDecodeClass:[IGNCommentListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [weakSelf.tableView ig_endHeaderRefreshing];
        [weakSelf.tableView ig_endFooterRefreshing];
        
        if (responseObject) {
            IGNCommentListResp *resp = responseObject;
            IGNCommentListModel *model = resp.data;
            
            NSMutableArray *tmpArr = [NSMutableArray arrayWithArray:model.comments];
            if (tmpArr && tmpArr.count > 0) {
                [weakSelf setupFooter];
            } else {
                [weakSelf.tableView ig_endFooterRefreshingWithNoMoreData];
            }
            
            if (weakSelf.page == 0) {
                weakSelf.hotComments = [NSMutableArray arrayWithArray:model.hotComments];
                weakSelf.newsComments = tmpArr;
            } else {
                [weakSelf.newsComments addObjectsFromArray:tmpArr];
            }
            weakSelf.lastQueryId = model.lastQueryId;
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
                weakSelf.title = [NSString stringWithFormat:@"评论(%@)", model.count];
            });
        }
    }];
}

- (void)setupFooter {
    __weak typeof(self) weakSelf = self;
    [self.tableView ig_setFooterWithRefreshingBlock:^{
        weakSelf.page++;
        [weakSelf dataRequest];
    }];
}

- (void)createUI {
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    [self.view addSubview:self.imView];
}

- (UIView *)imView {
    if(!_imView) {
        _imView = [[UIView alloc] initWithFrame:CGRectMake(0, KSCREENHEIGHT-50, KSCREENWIDTH, 50)];
        _imView.backgroundColor = [UIColor whiteColor];
        UIImageView *msg = [[UIImageView alloc] initWithFrame:CGRectMake(15, 0, 25, 25)];
        msg.image = [UIImage imageNamed:@"home_dian"];
        msg.contentMode = UIViewContentModeScaleAspectFit;
        [_imView addSubview:msg];
        msg.centerY = _imView.height/2;
        
        _imText = [[IWTextView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 50)];
        _imText.width = _imView.width-msg.right-5;
        _imText.placeholder = NSLocalizedString(@"comment", nil);
        _imText.contentInset = UIEdgeInsetsMake(7, 0, 7, 0);
        _imText.font = [UIFont systemFontOfSize:15];
        _imText.delegate = self;
        _imText.returnKeyType = UIReturnKeySend;
        _imText.x = msg.right+5;
        [_imView addSubview:_imText];
        
    }
    return _imView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if ([[[UIDevice currentDevice] systemVersion] floatValue]>= 11.0)
        {
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
        }
        __weak typeof(self) weakSelf = self;
        [self.tableView ig_setHeaderWithRefreshingBlock:^{
            weakSelf.page = 0;
            weakSelf.lastQueryId = @"";
            [weakSelf dataRequest];
        }];
    }
    return _tableView;
}

#pragma mark --<UITableViewDelegate, UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        if (moreSelected) {
            return self.hotComments.count;
        } else {
            if (self.hotComments.count > 3) {
                return 3;
            } else {
                return self.hotComments.count;
            }
        }
    } else if (section == 2) {
        return self.newsComments.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        IGCommentZuoPinCell *cell = [IGCommentZuoPinCell cellWithTableView:tableView];
        if (self.type == IGCommentPageTypeZuopin) {
            IGArtWorkModel *model = (IGArtWorkModel *)_baseModel;
            cell.model = model;
        }
        return cell;
    }
    
    IGCommentCell *cell = [IGCommentCell cellWithTableView:tableView];
    IGCommentBean *model = [IGCommentBean new];
    if (indexPath.section == 1) {
        model = [self.hotComments objectAtIndex:indexPath.row];
    } else if (indexPath.section == 2) {
        model = [self.newsComments objectAtIndex:indexPath.row];
    }
    [cell configCellWithModel:model];
    __weak typeof(self) weakSelf = self;
    cell.likeBlock = ^{
        [weakSelf liekComment:model.commentId];
    };
    cell.delBlock = ^{
        [weakSelf delComment:model.commentId];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (self.type == IGCommentPageTypeZuopin) {
            IGWorkDetailModel *model = (IGWorkDetailModel *)_baseModel;
            if ([model.plates intValue] == 1) {
                return 261.f;
            } else {
                return 425.f;
            }
        } else if(self.type == IGCommentPageTypeHuaDan){
            return 125.f;
        }
    }
    
    IGCommentBean *model = [self.hotComments objectAtIndex:indexPath.row];
    if (indexPath.section == 1) {
    } else if (indexPath.section == 2) {
        model = [self.newsComments objectAtIndex:indexPath.row];
    }
    CGFloat cell_height = [IGCommentCell hyb_heightForTableView:self.tableView config:^(UITableViewCell *sourceCell) {
        IGCommentCell *cell = (IGCommentCell *)sourceCell;
        [cell configCellWithModel:model];
    } cache:^NSDictionary *{
        NSDictionary *cache = @{kHYBCacheUniqueKey : [NSString stringWithFormat:@"k%@", model.commentId],
                                kHYBCacheStateKey : @"",
                                kHYBRecalculateForStateKey : @(YES)};
        model.shouldUpdateCache = NO;
        return cache;
    }];
    cell_height += 15;
    return cell_height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if ((section == 1 && self.hotComments.count) ||  (section == 2 && self.newsComments.count)) {
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 50.f)];
        bgView.backgroundColor = [UIColor c3Color];
        
        UILabel *titleLabel = [UILabel new];
        [bgView addSubview:titleLabel];
        titleLabel.font = [UIFont font18];
        titleLabel.textColor = [UIColor c4Color];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(10);
            make.right.mas_equalTo(-10);
            make.top.bottom.mas_equalTo(0);
        }];
        if (section == 1) {
            titleLabel.text = @"热门评论";
        } else if (section == 2) {
            titleLabel.text = @"最新评论";
        }
        
        return bgView;
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 1 && self.hotComments.count > 3) {
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 50.f)];
        UIButton *moreButton = [UIButton new];
        [bgView addSubview:moreButton];
        [moreButton setTitleColor:[UIColor c4Color] forState:UIControlStateNormal];
        [moreButton setTitle:@"全部热门评论" forState:UIControlStateNormal];
        [moreButton setImage:[UIImage imageNamed:@"切图 QH 20160704-12"] forState:UIControlStateNormal];
        __weak typeof(self) weakSelf = self;
        [moreButton setTapActionWithBlock:^{
            moreSelected = !moreSelected;
            [weakSelf.tableView reloadData];
        }];
        [moreButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
        
        return bgView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ((section == 1 && self.hotComments.count) || (section == 2 && self.newsComments.count)) {
        return 50.f;
    }
    
    return 0.1f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1 && self.hotComments.count > 3) {
        if (self.hotComments.count > 3) {
            return 50.f;
        } else {
            return 10.f;
        }
    }
    return 0.1f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (isRecomment) {
        _replayTheSeletedCellModel = nil;
        isRecomment = NO;
        [_imText endEditing:YES];
        return;
    }
    
    if (indexPath.section == 0) {
        return;
    } else if (indexPath.section == 1) {
        _replayTheSeletedCellModel = self.hotComments[indexPath.row];
        isTop = NO;
    } else {
        _replayTheSeletedCellModel = self.newsComments[indexPath.row];
        isTop = NO;
    }
    NSString *placeholder = [NSString stringWithFormat:@"@%@:", _replayTheSeletedCellModel.commentUserNick];
    isRecomment = YES;
    
    currtOff = tableView.contentOffset.y;
    selRect = [tableView rectForRowAtIndexPath:indexPath];
    if (_imText.isFirstResponder) {
        [self check:selRect];
    }
    [_imText becomeFirstResponder];
    _imText.placeholder = placeholder;
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (![textView isKindOfClass:[IWTextView class]]) {
        return NO;
    }
    if ([text isEqualToString:@"\n"]) {
        [self sendAcion];
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (![textView isKindOfClass:[IWTextView class]]) {
        return;
    }
    UITextRange *markedRange = [textView markedTextRange];
    if (markedRange) {
        return;
    }
    if (textView.text.length > 50) {
        [self presentMessageTips:NSLocalizedString(@"No more than 50 characters.", nil)];
        NSRange range = [textView.text rangeOfComposedCharacterSequenceAtIndex:50];
        textView.text = [textView.text substringToIndex:range.location];
    }
}

- (void)keyboardChangeFrame:(NSNotification *)not {
    CGRect end = [not.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView animateWithDuration:[not.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        _imView.bottom = end.origin.y;
    } completion:^(BOOL finished) {
    }];
}

- (void)keyboardShow:(NSNotification *)not
{
//    CGRect end = [not.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//    CGFloat h = end.origin.y-50;
//    CGFloat value = selRect.origin.y-currtOff;
//    CGFloat of = h-value;
//    [UIView animateWithDuration:.2 animations:^{
//        if (isTop) {
//            [self.tableView setContentOffset:CGPointMake(0, currtOff-of)];
//        } else {
//            [self.tableView setContentOffset:CGPointMake(0, currtOff-of+selRect.size.height)];
//        }
//    }];
}

- (void)check:(CGRect)rect
{
    CGFloat h = _imView.y;
    CGFloat value = rect.origin.y-currtOff;
    CGFloat of = h-value;
    [UIView animateWithDuration:.2 animations:^{
        if (isTop) {
            [self.tableView setContentOffset:CGPointMake(0, currtOff-of)];
        } else {
            [self.tableView setContentOffset:CGPointMake(0, currtOff-of+selRect.size.height)];
        }
    }];
}

- (void)keyboardHide:(NSNotification *)not
{
    [self.tableView setContentOffset:CGPointMake(0, currtOff)];
}

#pragma mark - 发表评论
- (void)sendAcion {
    [self.view endEditing:YES];
    if (_imText.text.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Add your comments", nil)];
        return;
    }
    
    if (_imText.text.length > 300) {
        [self presentMessageTips:NSLocalizedString(@"Exceeding max word count. Input Not Available", nil)];
        
        return;
    }
    
    IGNCommentType nCommentType = IGNCommentTypeFirst;
    if (self.replayTheSeletedCellModel) {
        nCommentType = IGNCommentTypeSecond;
    }

    IGSubmitCommentApi *submitApi = [IGSubmitCommentApi new];
    submitApi.type = self.type;
    submitApi.productId = self.productId;
    if (self.replayTheSeletedCellModel) {
        submitApi.parentId = self.replayTheSeletedCellModel.commentId;
    }
    submitApi.content = _imText.text;
    __weak typeof(self) weakSelf = self;
    [submitApi startWithDecodeClass:[IGSubmitCommentResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            [weakSelf dataRequest];
            weakSelf.imText.text = @"";
        }
    }];
}

- (void)liekComment:(NSString *)commentId {
    IGNCommentZanApi *zanApi = [IGNCommentZanApi new];
    zanApi.type = self.type;
    zanApi.commentId = commentId;
    zanApi.isLike = @"1";
    __weak typeof(self) weakSelf = self;
    [zanApi startWithDecodeClass:[IGNCommentZanResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            [weakSelf dataRequest];
        }
    }];
}

- (void)delComment:(NSString *)commentId {
    IGNCommentDelApi *delApi = [IGNCommentDelApi new];
    delApi.type = self.type;
    delApi.commentId = commentId;
    __weak typeof(self) weakSelf = self;
    [delApi startWithDecodeClass:[IGNCommentDelResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            [weakSelf dataRequest];
        }
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
